package com.ra.dao;

import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.annotation.Propagation;

import com.ra.model.user.UserProfile;
import com.ra.util.Ran;

final public class LoginDAOImpl extends AbstractDAO implements LoginDAO {
	private static final Logger logger = Logger.getLogger(LoginDAOImpl.class);

	@Transactional(propagation = Propagation.REQUIRED, readOnly = true)
	public UserProfile getUser(String userName, String password) {
		logger.debug(getSessionFactory().toString());
		logger.debug(getSessionFactory().getCurrentSession());
		Session session = getSessionFactory().getCurrentSession();
		Query query = session
				.createQuery("FROM UserProfile WHERE USERID = :username AND PASSWORD = :password AND ACTIVE = 1");
		query.setParameter("username", userName);
		query.setParameter("password", password);
		UserProfile user = (UserProfile) query.uniqueResult();
		logger.debug("After executing the query");
		if (logger.isDebugEnabled()) {
			String userDetails = (user == null) ? "No such user" : user
					.toString();
			logger.debug(String.format("Username: %s, Password: %s => %s",
					userName, password, userDetails));
		}
		return user;
	}

	@Transactional(propagation = Propagation.REQUIRED, readOnly = true)
	public UserProfile getUser(String userName) {
		logger.debug(getSessionFactory().toString());
		logger.debug(getSessionFactory().getCurrentSession());
		Session session = getSessionFactory().getCurrentSession();
		Query query = session
				.createQuery("FROM UserProfile WHERE USERID = :username");
		query.setParameter("username", userName);
		UserProfile user = (UserProfile) query.uniqueResult();
		logger.debug("After executing the query");
		if (logger.isDebugEnabled()) {
			String userDetails = (user == null) ? "No such user" : user
					.toString();
			logger.debug(String.format("Username: %s => %s", userName,
					userDetails));
		}
		return user;
	}

	@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
	public void registerUser(UserProfile user) {
		Ran r = new Ran();
		user.setVerificationCode(r.genRan());
		// user.setPassword("ra123");
		Session session = getSessionFactory().getCurrentSession();
		session.save(user);
	}

	@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
	public void updateUser(UserProfile user) {
		Session session = getSessionFactory().getCurrentSession();
		session.update(user);
	}
}
